import { getToken, setToken, removeToken, setTimeStamp } from '@/utils/auth'
import { login, userProfile, getProfileById } from '@/api/user'
import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    userInfo: {}
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  REMOVE_TOKEN: (state) => {
    state.token = ''
    removeToken()
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_USERINFO(state, user) {
    state.userInfo = user
  }
}

const actions = {
  // 用户登录接口
  async login({ commit }, userInfo) {
    const res = await login(userInfo)
    // console.log(res)
    commit('SET_TOKEN', res)
    setToken(res)
    // 获取到token后记录一下时间
    setTimeStamp()
  },
  // 获取用户信息
  async getInfo({ commit }) {
    const res = await userProfile()
    const res1 = await getProfileById(res.userId)
    // console.log(res, res1)
    commit('SET_USERINFO', { ...res, ...res1 })
    return res
  },
  // 用户退出登录
  logout({ commit }) {
    commit('REMOVE_TOKEN')
    commit('SET_USERINFO', {})
    resetRouter()
    commit('permission/setRoutes', [], { root: true })
  },

  // 重置token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

